﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ComTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
            serialPort1.PortName = "COM3";
            serialPort1.BaudRate = 38400;//9600;
            serialPort1.Open();
        }

        public delegate void XD();

        void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            Invoke(new XD(Recv));
        }

        void Recv()
        {
            string s = "";
            string hex = "";
            while (serialPort1.BytesToRead > 0)
            {
                int d = serialPort1.ReadChar();
                s += "" + (char)d + " ";
                hex += string.Format("0x{0:x4} ", d);
            }
            richTextBox_recv.Text += "s[" + s + "]\n";
            richTextBox_recv.Text += "h[" + hex + "]\n\n";
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            serialPort1.WriteLine(richTextBox_send.Text);
            richTextBox_send.Clear();
        }
    }
}
